#pragma once
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include "logmessage.hpp"

#include <iostream>
using namespace std;

class Socket
{
    int _sockfd;
    static const int s_backlog = 20;

public:
    Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == -1)
        {
            LogMessage(Fatal, "socket(%d): %s", errno, strerror(errno));
            exit(errno);
        }
        // 设置端口号复用，防止因为TIME_WAIT状态导致的bind error
        int opt = 1;                                                                                   //!!!
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEPORT | SO_REUSEADDR, &opt, sizeof(opt)); 
        LogMessage(Debug, "create socket success!");
    }

    void Bind(const std::string &ip, uint16_t port)
    {
        sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = inet_addr(ip.c_str());

        if (bind(_sockfd, (sockaddr *)&local, sizeof(local)) == -1)
        {
            LogMessage(Fatal, "bind(%d): %s", errno, strerror(errno));
            exit(errno);
        }
        LogMessage(Debug, "bind socket success!");
    }

    void Listen()
    {
        if (listen(_sockfd, s_backlog))
        {
            LogMessage(Fatal, "listen(%d): %s", errno, strerror(errno));
            exit(errno);
        }
        LogMessage(Debug, "listen socket success!");
    }

    int Accept(std::string *ip, uint16_t *port)
    {
        sockaddr_in src;
        socklen_t len;
        int svcsock = accept(_sockfd, (sockaddr *)&src, &len);
        if (svcsock == -1)
        {
            LogMessage(Error, "accept(%d): %s", errno, strerror(errno));
            return -1;
        }
        if (ip != nullptr)
            *ip = inet_ntoa(src.sin_addr);
        if (port != nullptr)
            *port = ntohs(src.sin_port);
        return svcsock;
    }

    void Connect(const std::string &ip, uint16_t port)
    {
        sockaddr_in dst;
        memset(&dst, 0, sizeof(dst));
        dst.sin_family = AF_INET;
        dst.sin_port = htons(port);
        dst.sin_addr.s_addr = inet_addr(ip.c_str());

        if (connect(_sockfd, (sockaddr *)&dst, sizeof(dst)) == -1)
        {
            LogMessage(Fatal, "connect(%d): %s", errno, strerror(errno));
            exit(errno);
        }
    }

    int getsock()
    {
        return _sockfd;
    }

    ~Socket()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
};